from django.shortcuts import render
from django.views import View
from django.http import JsonResponse

from .forms import UserFavForm
from .models import UserFavorite
from apps.coures.models import Course
from apps.organiztion.models import CourseOrg, Teacher

# Create your views here.
class AddFavView(View):
    def post(self, request, *args, **kwargs):
        '''
        用户收藏、用户取消收藏
        1. 判断用户是否登录，没登录就跳转登录页面
        2. 判断表单验证是否通过
        2.1 表单验证通过：判断 fav_type 收藏类型
        '''
        if not request.user.is_authenticated:
            return JsonResponse({
                'status': 'fail',
                'msg': '用户未登录'
            })

        # 验证表单
        user_fav_form = UserFavForm(request.POST)
        if user_fav_form.is_valid():
            fav_id = user_fav_form.cleaned_data['fav_id']
            fav_type = user_fav_form.cleaned_data['fav_type']

            # 判断用户是否收藏
            exised_records = UserFavorite.objects.filter(user=request.user, fav_id=fav_id, fav_type=fav_type)
            # 如果用户收藏了，再次点击则取消收藏
            if exised_records:
                exised_records.delete()

                # 用户取消收藏后，对应的收藏类别的数据的 收藏数减一
                if fav_type == 1:
                    course = Course.objects.get(id=fav_id)
                    course.fav_nums -= 1
                    course.save()
                if fav_type == 2:
                    course_org = CourseOrg.objects.get(id=fav_id)
                    course_org.fav_nums -= 1
                    course_org.save()
                if fav_type == 3:
                    teacher = Teacher.objects.get(id=fav_id)
                    teacher.fav_nums -= 1
                    teacher.save()
                return JsonResponse({
                    'status': 'success',
                    'msg': '收藏'
                })
            # 用户没有收藏
            else:
                user_fav = UserFavorite()
                user_fav.fav_id = fav_id
                user_fav.fav_type = fav_type
                user_fav.user = request.user
                user_fav.save()

                return JsonResponse({
                    'status': 'success',
                    'msg': '已收藏'
                })
        # 表单验证不通过
        else:
            return JsonResponse({
                'status': 'fail',
                'msg': '参数错误'
            })
